package org.wang.generalcode.modules.gen.controller;

import cn.hutool.core.io.IoUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.wang.generalcode.modules.gen.pojo.vo.PreviewVO;
import org.wang.generalcode.modules.gen.service.GeneratorService;
import org.wang.generalcode.support.result.Result;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;

@RestController
@AllArgsConstructor
@RequestMapping("/generator")
@Schema(description = "代码生成", name = "代码生成接口")
public class GeneratorController {

    private final GeneratorService generatorService;

    /**
     * 生成代码（zip压缩包）
     */
    @ApiOperationSupport(order = 1)
    @Schema(description = "生成代码（zip压缩包）", example = "传入tableIds")
    @GetMapping("/download")
    public void download(String tableIds, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        // 生成代码
        for (String tableId : tableIds.split(",")) {
            generatorService.downloadCode(Long.parseLong(tableId), zip);
        }

        IoUtil.close(zip);

        // zip压缩包数据
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"wz.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

    /**
     * 生成代码（自定义目录）
     */
    @ApiOperationSupport(order = 1)
    @Schema(description = "分页查询", example = "传入query")
    @PostMapping("/code")
    public Result<String> code(@RequestBody Long[] tableIds) throws Exception {
        // 生成代码
        for (Long tableId : tableIds) {
            generatorService.generatorCode(tableId);
        }

        return Result.success();
    }

    /**
     * 预览代码
     */
    @ApiOperationSupport(order = 1)
    @Schema(description = "预览代码", example = "传入tableId")
    @GetMapping("/preview")
    public Result<List<PreviewVO>> preview(@Parameter(name = "表格id", required = true) @RequestParam Long tableId) throws Exception {
        List<PreviewVO> results = generatorService.preview(tableId);
        return Result.success(results);
    }
}
